package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.LogTypeEnum;
import net.xdclass.model.LogRecord;
import net.xdclass.service.LogService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author: wangzhan
 * @Description: TODO
 * @DateTime: 2025/1/12 22:03
 **/
@Service
@Slf4j
public class LogServiceImpl implements LogService {
    private static final String TOPIC_NAME = "ods_link_visit_topic";
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Override
    public void recordShortLinkLog(HttpServletRequest request, String shortLinkCode, Long accountNo) {
        String ip = CommonUtil.getIpAddr(request);
        Map<String, String> allRequestHeader = CommonUtil.getAllRequestHeader(request);
        Map<String, String> availableHeader = new HashMap<>();
        availableHeader.put("user-agent", allRequestHeader.get("user-agent"));
        availableHeader.put("referer", allRequestHeader.get("referer"));
        availableHeader.put("accountNo", accountNo.toString());
        LogRecord logRecord = LogRecord.builder()
                    .eventType(LogTypeEnum.SHORT_LINK_TYPE.name())
                    .data(availableHeader).ip(ip).ts(CommonUtil.getCurrentTimestamp())
                    .bizId(shortLinkCode).build();
        String logJson = JsonUtil.obj2Json(logRecord);
        log.info(logJson);
        // 发送到kafka
        kafkaTemplate.send(TOPIC_NAME, logJson);
        //return JsonData.buildSuccess();
        }
}
